<?php

namespace app\admin\command;

use app\admin\model\cms\GrapevineModel;
use app\api\service\FetchArticleService;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Exception;

/**
 * 根据指定url使用Api爬取小道消息并更新数据库
 * Class CaptureGrapevine
 * @package app\admin\command
 */
class CaptureGrapevine extends Command
{
    protected function configure()
    {
        $this->setName('captureGrapevine')->setDescription('api抓取小道消息');
    }

    protected function execute(Input $input, Output $output)
    {
        // 执行具体的任务逻辑
        $data = GrapevineModel::where('status',0)
            ->where('failure_count','<',3)
            ->select();

        $service = new FetchArticleService();//api根据链接抓取文章
            foreach ($data as $v){
                $getArticle = $this->getArticle($service,$v['form_url']);
                if ($getArticle['code'] == 200){
                    $update_data = [
                        'content' => $getArticle['html_content'],
                        'status' => 1,
                        'failure_count' => 0,
                    ];
                }else{
                    $update_data = [
                        'content' => $getArticle['html_content'],
                        'status' => 2,
                        'remark' => $getArticle['msg'],
                        'failure_count' => 3,
                    ];
                }
                $success = GrapevineModel::where('id',$v['id'])->update($update_data);
            }
    }

    private function getArticle($obj, $url, $num = 1)
    {

        $res = [
            'code'=>200,
            'msg'=>'success',
            'title'=>'',
            'html_content'=>'',
        ];
        $fetchArticle = $obj->fetchArticle($url);
        if ($fetchArticle['code'] == 200){
            $res['title'] = $fetchArticle['title'];
            $res['html_content'] = $fetchArticle['html_content'];
        }else{
            $res['code'] = 500;
            $res['msg'] = $fetchArticle['msg'];
            if ($num < 4){
                $this->getArticle($obj, $url,($num+1));
            }
        }

        return $res;
    }
}